package domain

import (
	"AcsGo/internal/util"
	"fmt"
)

type QueryRequest struct {
	Code            util.Field
	StatusCode      util.Field
	MaxPrintWidth   util.Field
	ProtocolVersion util.Field
}

func HandleQueryRequest(str string) (*QueryRequest, error) {
	if str == "" {
		return nil, fmt.Errorf("str is empty")
	}
	var query = QueryRequest{
		Code: util.Field{
			Value:  "99",
			Length: 2,
		},
		StatusCode: util.Field{
			Value:  "",
			Length: 1,
		},
		MaxPrintWidth: util.Field{
			Value:  "",
			Length: 3,
		},
		ProtocolVersion: util.Field{
			Value:  "",
			Length: 4,
		},
	}

	length := query.Code.Length + query.StatusCode.Length + query.MaxPrintWidth.Length + query.ProtocolVersion.Length
	if len(str) < length {
		return nil, fmt.Errorf("str is too short")
	}

	strTemp := query.Code.GetValue(str)
	strTemp = query.StatusCode.GetValue(strTemp)
	strTemp = query.MaxPrintWidth.GetValue(strTemp)
	_ = query.ProtocolVersion.GetValue(strTemp)
	return &query, nil
}

type QueryResponse struct {
	Code             util.Field
	OnLineStatus     util.Field
	CheckInOk        util.Field
	CheckOutOk       util.Field
	AcsRenewalPolicy util.Field
	StatusUpdateOk   util.Field
	OffLineOk        util.Field
	TimeOutPeriod    util.Field
	RetriesAllowed   util.Field
	DateTimeSync     util.Field
	InstitutionId    util.FieldPrefix
	ScreenMessage    util.FieldPrefix
	PrintLine        util.FieldPrefix
	Validate         util.FieldPrefix
}

func (q QueryResponse) StringFormat() (string, error) {
	sb, err := util.ConcatenateFields(q)
	if err != nil {
		return "", err
	}
	return sb, nil
}

func InitQueryResponse(screenMessage string) *QueryResponse {
	var queryResponse = QueryResponse{
		Code:             util.Field{Value: "98", Length: 2},
		OnLineStatus:     util.Field{Value: "Y", Length: 1},
		CheckInOk:        util.Field{Value: "Y", Length: 1},
		CheckOutOk:       util.Field{Value: "Y", Length: 1},
		AcsRenewalPolicy: util.Field{Value: "Y", Length: 1},
		StatusUpdateOk:   util.Field{Value: "Y", Length: 1},
		OffLineOk:        util.Field{Value: "N", Length: 1},
		TimeOutPeriod:    util.Field{Value: "180", Length: 3},
		RetriesAllowed:   util.Field{Value: "180", Length: 3},
		DateTimeSync:     util.Field{Value: util.GetCurrentTimeInFormat(), Length: 18},
		InstitutionId:    util.FieldPrefix{Value: "", Prefix: "AO", Suffix: util.PrefixLink},
		ScreenMessage:    util.FieldPrefix{Value: "", Prefix: "AF", Suffix: util.PrefixLink},
		PrintLine:        util.FieldPrefix{Value: "", Prefix: "AG", Suffix: util.PrefixLink},
		Validate:         util.FieldPrefix{Value: "1AZf5f5", Prefix: "AY", Suffix: util.PrefixLink},
	}
	if screenMessage == "" {
		queryResponse.ScreenMessage.Value = "连接ACS_Server成功"
	}
	return &queryResponse
}
